<template>
  <div>
    <!-- 商品缩略图添加 -->
    <el-dialog
      title="Add/Select product pictures"
      :visible.sync="thumbnailVisible"
      append-to-body
      width="780px"
      @close="choseThumbnail"
    >
      <div>
        <el-tabs v-model="activeName" type="card" @tab-click="tabChange">
          <el-tab-pane label="Add Images" name="addImage">
            <el-upload
              action=""
              list-type="picture-card"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :http-request="uploadImg"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <p style="padding-top: 5px;color:red;">
              ps：Only {{ limitCount }} images are allowed to be uploaded
            </p>
          </el-tab-pane>
          <el-tab-pane label="Select Images" name="chooseImage">
            <div
              v-loading="loading"
              class="imagesList"
              style="min-height: 100px;"
            >
              <div
                v-for="(item, index) in tableData"
                :key="index"
                class="imagesItem"
              >
                <el-image
                  class="productImg big"
                  :src="item.uri.indexOf('http')===0?item.uri:imgPrefix + item.uri + imgSuffix"
                  @click="toggleSelect(item)"
                />
              </div>
              <div v-if="!loading && tableData.length === 0" class="noTip">
                No images
              </div>
            </div>
            <el-pagination
              v-if="!loading"
              :current-page="currentPage"
              :page-size="pageSize"
              layout="total, prev, pager, next, jumper"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </el-tab-pane>
        </el-tabs>
        <!-- 已选择 -->
        <div class="tip">
          <div class="flex">
            <div v-if="imageUri" class="item">
              <el-image
                class="productImg big"
                :src="imageUri.indexOf('http')===0?imageUri:imgPrefix + imageUri + imgSuffix"
                @click="toProview(imgPrefix + imageUri)"
              />
              <el-button @click="removeImg">Remove</el-button>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="choseThumbnail">Cancel</el-button>
        <el-button
          :disabled="!imageId"
          type="primary"
          @click="choseThumbnail(imageId, imageUri)"
        >Confirm</el-button>
      </div>

      <!-- 图片预览 -->
      <proview-img v-if="proviewUrl" :src="proviewUrl" @close="closeProview" />
    </el-dialog>
  </div>
</template>

<script>
import { productImagesPage, productImagesAdd } from '@/api/product';
import ProviewImg from '@/components/Proview/proviewImg';
export default {
  components: {
    ProviewImg
  },
  props: {
    storeId: {
      type: Number,
      required: true
    },
    // eslint-disable-next-line vue/require-prop-types
    selectedUri: {
      required: true
    },
    // eslint-disable-next-line vue/require-prop-types
    selectedId: {
      required: true
    }
  },
  data() {
    return {
      limitCount: 1,
      imageId: this.selectedId,
      imageUri: this.selectedUri,
      thumbnailVisible: true,
      activeName: 'addImage',
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 24,
      total: 0,
      proviewUrl: '',
      nameLength: 100 // 图片名字最大长度
    };
  },
  methods: {
    getList() {
      this.loading = true;
      productImagesPage({
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        storeId: this.storeId
      }).then(res => {
        this.loading = false;
        this.tableData = res.data.data;
        this.total = res.data.totalCount;
      });
    },
    tabChange(obj) {
      if (obj.index === '1') {
        // 选择图片
        this.getList();
      }
    },
    datadragEnd(evt) {
      evt.preventDefault();
    },
    beforeUpload(file) {
      // 仅有类型判断，未加大小判断
      const isIMG =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png';
      if (!isIMG) {
        this.$message.error(
          'Upload images only support JPG, jpeg, PNG format!'
        );
      }
      return isIMG;
    },
    uploadImg(obj) {
      if (obj.file.name.length > this.nameLength) {
        obj.file.name = obj.file.name.substring(
          obj.file.name.length - this.nameLength
        );
      }
      const params = {
        fileSize: obj.file.size,
        storeId: this.storeId,
        categoryId: 0,
        name: obj.file.name
      };
      const reader = new FileReader();
      reader.readAsDataURL(obj.file);
      reader.onload = () => {
        this.showImage = true;
        params.fileContent = reader.result;
        productImagesAdd(params).then(res => {
          if (res.code === 200) {
            this.$message.success(res.message);
            this.imageId = res.data.id;
            this.imageUri = res.data.uri;
          }
        });
      };
    },
    removeImg() {
      this.imageId = null;
      this.imageUri = null;
    },
    toggleSelect(item) {
      this.imageId = item.id;
      this.imageUri = item.uri;
    },
    toProview(url) {
      // 预览图片
      this.proviewUrl = url;
    },
    closeProview() {
      this.proviewUrl = '';
      document.querySelector('body').removeAttribute('style');
    },
    choseThumbnail(id, uri) {
      this.$emit('emitClose', [id, uri]);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
.tip {
  border-top: 1px solid #ddd;
  margin-top: 10px;
  padding-top: 20px;
  .flex {
    overflow: hidden;
    margin-top: 10px;
    .item {
      float: left;
      display: flex;
      flex-direction: column;
      margin-right: 10px;
      .el-button {
        width: 48px;
        box-sizing: content-box;
      }
    }
  }
}
.el-tabs--card {
  >>> .el-tabs__content {
    overflow: inherit;
    .chooseBtn {
      position: absolute;
      right: 10px;
      top: -53px;
    }
  }
}
.el-table {
  margin-bottom: 10px;
}
.imagesList {
  overflow: hidden;
  .imagesItem {
    position: relative;
    float: left;
    width: 80px;
    height: 80px;
    margin-right: 14px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
    border-radius: 4px;
    overflow: hidden;
    &:nth-child(8n) {
      margin-right: 0;
    }
  }
}
.noTip {
  line-height: 100px;
  text-align: center;
  color: #999;
}
.el-pagination {
  position: static;
  padding: 0;
}
</style>
